package com.demo.systemmonitor;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.demo.systemmonitor.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class HistoryDataViewerActivity extends Activity {
    private static final String TAG = "HistoryDataViewer";
    
    private ListView fileListView;
    private Button btnSelectFile, btnViewChart;
    private TextView tvSelectedFile, tvTimeRange;
    private TextView tvDataTimeRange;
    
    private List<File> dataFiles;
    private File selectedFile;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_data_viewer);
        
        initViews();
        loadDataFiles();
    }
    
    private void initViews() {
        fileListView = findViewById(R.id.listview_data_files);
        btnSelectFile = findViewById(R.id.btn_select_file);
        btnViewChart = findViewById(R.id.btn_view_chart);
        tvSelectedFile = findViewById(R.id.tv_selected_file);
        tvTimeRange = findViewById(R.id.tv_time_range);
        tvDataTimeRange = findViewById(R.id.tv_data_time_range); // 新增
        
        btnSelectFile.setOnClickListener(v -> selectTimeRange());
        btnViewChart.setOnClickListener(v -> viewChart());
    }
    
    private void loadDataFiles() {
        // 使用静态方法获取数据目录
        File dataDir = SystemDataStorageService.getDataDirectory(this);
        Log.d(TAG, "Looking for data files in: " + dataDir.getAbsolutePath());
        
        if (dataDir.exists()) {
            // 使用静态方法获取数据文件
            File[] files = SystemDataStorageService.getDataFiles(dataDir);
            Log.d(TAG, "Found " + files.length + " CSV files");
            
            if (files.length > 0) {
                dataFiles = new ArrayList<>();
                for (File file : files) {
                    dataFiles.add(file);
                    Log.d(TAG, "Added file: " + file.getName());
                }
            }
        } else {
            Log.d(TAG, "Data directory does not exist: " + dataDir.getAbsolutePath());
        }
        
        // 显示文件列表
        if (dataFiles != null && !dataFiles.isEmpty()) {
            ArrayAdapter<File> adapter = new ArrayAdapter<File>(this, 
                android.R.layout.simple_list_item_1, dataFiles) {
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    TextView textView = (TextView) super.getView(position, convertView, parent);
                    textView.setTextColor(Color.WHITE);  // 设置文字为白色
                    textView.setBackgroundColor(Color.TRANSPARENT);  // 设置背景透明
                    return textView;
                }
            };
            fileListView.setAdapter(adapter);
            
            fileListView.setOnItemClickListener((parent, view, position, id) -> {
                selectedFile = dataFiles.get(position);
                tvSelectedFile.setText("已选择: " + selectedFile.getName());
                
                // 显示文件信息
                showFileInfo(selectedFile);
            });
        } else {
            Toast.makeText(this, "没有找到数据文件\n请先运行CPU监控生成数据", Toast.LENGTH_LONG).show();
        }
    }
    
    private void showFileInfo(File file) {
        if (file != null && file.exists()) {
            long fileSize = file.length();
            long lastModified = file.lastModified();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            
            String info = String.format(Locale.getDefault(), 
                "文件大小: %d 字节\n最后修改: %s", 
                fileSize, 
                dateFormat.format(new Date(lastModified)));
            
            tvTimeRange.setText(info);
            
            // 解析数据时间范围
            parseDataTimeRange(file);
        }
    }
    
    private void selectTimeRange() {
        if (selectedFile == null) {
            Toast.makeText(this, "请先选择数据文件", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 启动时间范围选择器
        Intent intent = new Intent(this, TimeRangeSelectorActivity.class);
        intent.putExtra("file_path", selectedFile.getAbsolutePath());
        startActivityForResult(intent, 1001);
    }
    
    private void viewChart() {
        if (selectedFile == null) {
            Toast.makeText(this, "请先选择数据文件", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 直接启动图表查看器，显示三个图表
        Intent intent = new Intent(this, ChartViewerActivity.class);
        intent.putExtra("file_path", selectedFile.getAbsolutePath());
        intent.putExtra("data_type", "ALL"); // 显示所有类型数据
        startActivity(intent);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            // 时间范围选择完成，直接启动图表查看器
            String startTime = data.getStringExtra("start_time");
            String endTime = data.getStringExtra("end_time");
            
            if (startTime != null && endTime != null) {
                tvTimeRange.setText("时间范围: " + startTime + " - " + endTime);
                
                // 启动图表查看器
                Intent chartIntent = new Intent(this, ChartViewerActivity.class);
                chartIntent.putExtra("file_path", selectedFile.getAbsolutePath());
                chartIntent.putExtra("data_type", "ALL");
                chartIntent.putExtra("start_time", startTime);
                chartIntent.putExtra("end_time", endTime);
                startActivity(chartIntent);
            }
        }
    }

    // 新增方法：解析数据文件中的时间范围
    private void parseDataTimeRange(File file) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;
            String firstTime = null;
            String lastTime = null;
            boolean isHeader = true;
            
            while ((line = reader.readLine()) != null) {
                if (isHeader) {
                    isHeader = false;
                    continue;
                }
                
                String[] parts = line.split(",");
                if (parts.length >= 1) {
                    String timeStr = parts[0].trim();
                    if (firstTime == null) {
                        firstTime = timeStr;
                    }
                    lastTime = timeStr;
                }
            }
            reader.close();
            
            if (firstTime != null && lastTime != null) {
                // 从文件名提取日期
                String fileName = file.getName();
                String dateStr = fileName.substring(12, fileName.length() - 4); // 去掉 "system_data_" 和 ".csv"
                
                // 构建完整的时间显示
                String dataTimeRange = String.format("数据时间范围: %s %s - %s", 
                    dateStr, firstTime, lastTime);
                tvDataTimeRange.setText(dataTimeRange);
            } else {
                tvDataTimeRange.setText("数据时间范围: 无有效数据");
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error parsing data time range", e);
            tvDataTimeRange.setText("数据时间范围: 解析失败");
        }
    }
}